import PlaceHolderCpn from '@/components/PlaceHolderCpn';
import type { ProDescriptionsItemProps } from '@ant-design/pro-components';
import { useModel } from 'umi';
import { Avatar, Button, Tag } from 'antd';
import ModifyPassWord from './components/ModifyPassWord';
import UpdateSelfInfo from './components/UpdateSelfInfo';
import WxBindModal from './components/WxBind';
import { useEffect, useRef, useState } from 'react';
import { ProTable, ActionType, ProCard, ProDescriptions } from '@ant-design/pro-components';
import { BindedWxItem } from './types.d';
import { getUserResource, queryBindedList, unbindWx } from './service';
import ConfirmModal from '@/components/ConfirmModal';
import { Role } from '@/utils/types.d';

export default () => {
  const { initialState } = useModel('@@initialState');
  const [bindVisible, setBindVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const currUser = initialState?.currentUser;
  const userRole = currUser?.role;
  const [resource, setResource] = useState<{
    parkingLot: number;
    parkingSpot: number;
    patrolDevice: number;
    sensor: number;
  } | null>(null);
  useEffect(() => {
    if (userRole !== Role.ENTERPRISE) return;
    getUserResource().then((res) => {
      if (res.success && res.data) {
        setResource(res.data);
      }
    });
  }, []);
  const columns: ProDescriptionsItemProps<API.CurrentUser>[] = [
    {
      title: '用户账号',
      key: 'text',
      dataIndex: 'account',
    },
    {
      title: '用户角色',
      dataIndex: 'role',
      valueEnum: {
        0: <Tag>系统管理员</Tag>,
        1: <Tag>企业管理</Tag>,
        2: <Tag>企业员工</Tag>,
      },
    },
    {
      title: '所属公司',
      key: 'text',
      dataIndex: 'ownerName',
      render: (_, record) =>
        record.ownerId !== 'admin' ? (
          <span>{record.ownerName}</span>
        ) : (
          <PlaceHolderCpn text="系统" />
        ),
    },
    {
      title: '电子邮箱',
      key: 'text',
      dataIndex: 'email',
      render: (_, record) => record.email || <PlaceHolderCpn text="暂无数据" />,
    },
    {
      title: '密码设置',
      render: (_, record) => <ModifyPassWord id={record.id} />,
    },
    {
      title: '上次登录',
      key: 'date',
      dataIndex: 'lastLogin',
      valueType: 'dateTime',
    },
    {
      title: '绑定微信',
      key: 'button',
      render: () => (
        <Button
          type="primary"
          size="small"
          onClick={() => {
            setBindVisible(true);
          }}
        >
          扫码绑定
        </Button>
      ),
    },
  ];
  return (
    <ProCard
      title={'个人空间'}
      headerBordered
      bodyStyle={{
        padding: '20px 10vw',
      }}
      direction="row"
    >
      <ProCard layout="center" colSpan="160px">
        <Avatar src="/user.svg" size={72} />
      </ProCard>
      <ProCard ghost direction="column">
        <ProCard>
          <h3 style={{ paddingBottom: '20px' }}>欢迎回来，{currUser?.userName}~</h3>
          <ProDescriptions column={2} dataSource={currUser} columns={columns} />
          <UpdateSelfInfo user={currUser} />
        </ProCard>
        {userRole === Role.ENTERPRISE && resource && (
          <ProTable
            headerTitle="企业资源"
            search={false}
            size="small"
            options={false}
            pagination={false}
            rowKey={'type'}
            columns={[
              {
                title: '资源类型',
                dataIndex: 'type',
                align: 'center',
              },
              {
                title: '资源数量',
                dataIndex: 'count',
                align: 'center',
              },
            ]}
            dataSource={[
              {
                type: '路段',
                count: resource.parkingLot,
              },
              {
                type: '泊位',
                count: resource.parkingSpot,
              },
              {
                type: '地磁设备',
                count: resource.sensor,
              },
              {
                type: '巡检设备',
                count: resource.patrolDevice,
              },
            ]}
          />
        )}
        <ProTable<BindedWxItem>
          headerTitle="已绑定微信列表"
          search={false}
          actionRef={actionRef}
          size="small"
          rowKey="_id"
          options={false}
          columns={[
            {
              title: '微信头像',
              dataIndex: 'headimgurl',
              align: 'center',
              render: (_, record) => <Avatar src={record.headimgurl} size={30} />,
            },
            {
              title: '微信昵称',
              dataIndex: 'nickname',
              align: 'center',
            },
            {
              title: '绑定时间',
              dataIndex: 'createTime',
              valueType: 'dateTime',
              align: 'center',
            },
            {
              title: '操作',
              align: 'center',
              dataIndex: '_id',
              valueType: 'option',
              render: (_, record, x, action) => {
                return (
                  <ConfirmModal
                    reload={() => action?.reload()}
                    operFunc={async () => await unbindWx(record._id)}
                    titleText="解绑微信"
                    text={`确定要解绑微信昵称为「${record.nickname}」的账号吗？`}
                    btnText="解绑"
                  />
                );
              },
            },
          ]}
          debounceTime={300}
          request={queryBindedList}
        />
      </ProCard>

      {bindVisible && (
        <WxBindModal
          visible={bindVisible}
          close={() => {
            actionRef.current?.reload();
            setBindVisible(false);
          }}
        />
      )}
    </ProCard>
  );
};
